package com.wise.service.portal.content.uploadresources;

import com.wise.entities.content.Article;
import com.wise.entities.content.Resource;
import com.wise.entities.content.ResourceGroup;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoPageList;
import com.wise.framework.restful.PageResultList;
import com.wise.framework.validation.Precondition;
import com.wise.model.content.resourcegroup.ResourceGroupType;
import com.wise.model.content.utils.AnsjUtil;
import com.wise.summer.v1.portal.content.uploadresources.ListUploadResources;
import com.wise.summer.v1.portal.content.uploadresources.SearchUploadResources;
import org.ansj.domain.Term;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.Arrays;
import java.util.List;

import static com.wise.model.content.ContentErrMsgs.Err_100100000004;

/**
 * @author hejiawei
 * @date 2020/9/23 14:58
 */
@Service
@SummerService
public class SearchUploadResourcesService implements SummerServiceBean<SearchUploadResources> {
    @Value("${azure.file.url}")
    private String url;

    @Override
    public void sum(SearchUploadResources summer) {
        SqlSelect select = SqlSelect.selec("*")
                .fromClassName(Resource.class, "res")
                .left_outer_join("upload_resource_groups gr on res.group_id=gr.id")
                .eq("gr." + ResourceGroup._groupType, ResourceGroupType.FILE.value())
                .eqLang("res." + Resource._lang);
        if (StringUtils.isNoneBlank(summer.getResourceName())) {
            //分词
            List<String> terms = Arrays.asList(org.apache.commons.lang.StringUtils.split(summer.getResourceName(), " "));
            for (int i = 0; i < terms.size(); i++) {
                select.like(Resource._resourceName, "%" + terms.get(i) + "%");
                if (terms.size() - i > 1) {
                    select.or();
                }
            }
        }
        select.order_by(Resource.UPLOAD_TIME + " desc");
        PageResultList<ListUploadResources.Result> list = DaoPageList.s(ListUploadResources.Result.class, select, summer.getStart(), summer.getLimit());
        Precondition.checkNotNull(list, Err_100100000004);
        if (StringUtils.isNotEmpty(url)) {
            for (ListUploadResources.Result result : list.getList()) {
                int index = result.getPath().lastIndexOf("/");
                String fileName = result.getPath().substring(index + 1);
                result.setPath(url + fileName);
            }
        }
        summer.setSummerResult(list);

    }
}
